package com.cnpinxi.controller.admin.user;

import com.cnpinxi.controller.base.BaseController;
import com.cnpinxi.def.Constant;
import com.cnpinxi.def.MessageConstant;
import com.cnpinxi.domain.AdminMenu;
import com.cnpinxi.domain.AdminUser;
import com.cnpinxi.domain.Role;
import com.cnpinxi.myRunTime.MyRunTimeExcption;
import com.cnpinxi.result.ResultObj;
import com.cnpinxi.service.AdminUserService;
import com.cnpinxi.service.MenuService;
import com.cnpinxi.service.RoleService;
import com.cnpinxi.tool.RandomValidateCode;
import com.cnpinxi.util.MD5Tools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * Created by Andrew  on 2017/2/26.
 */
@Controller
@RequestMapping(value = "/admin/user")
public class AdminUserController extends BaseController {
    /*@Autowired
    RedisCache redisCache;*/
    @Autowired
    RoleService roleService;
    @Autowired
    MenuService menuService;
    @Autowired
    AdminUserService adminUserService;

    @RequestMapping(value = "/showMenuList")
    public ModelAndView showMenuList(HttpServletRequest request) {
        ModelAndView mov = new ModelAndView();
        mov.setViewName("admin/menu/getMenuList");

        Map<String, String> map = this.showRequestParameters(request);
        map.put("menuParentId", "0");
        List<AdminMenu> menuList = menuService.getMenuList(map);

        mov.addObject("menuList", menuList);

        mov.addObject("bean", map);
        return mov;

    }

    @RequestMapping(value = "/getMenuList", method = RequestMethod.POST)
    @ResponseBody
    public String getMenuList(HttpServletRequest request) {

        ResultObj resultObj = new ResultObj();
        resultObj.setCode(ResultObj.CODE_FAIL);
        try {
            Map<String, String> map = this.showRequestParameters(request);

            List<AdminMenu> menuList = menuService.getMenuList(map);
            resultObj.setCode(ResultObj.CODE_SUCCESS);
            resultObj.setData(menuList);
            resultObj.setMsg("成功！");
        } catch (MyRunTimeExcption myRunTimeExcption) {

            resultObj.setMsg(myRunTimeExcption.getMessage());
            myRunTimeExcption.printStackTrace();
        } catch (Exception e) {
            resultObj.setMsg(e.getMessage());
            e.printStackTrace();
        }

        return resultObj.toJson();

    }



    @RequestMapping(value = "/gotoLogin")
    public ModelAndView gotoLogin(HttpServletRequest request) {
        ModelAndView mov = new ModelAndView();
        mov.setViewName("/admin/user/login");

        return mov;

    }

    @RequestMapping(value = "/getVerificatioCode")
    @ResponseBody
    public void getVerificationCode(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("image/jpeg");// 设置相应类型,告诉浏览器输出的内容为图片
        response.setHeader("Pragma", "No-cache");// 设置响应头信息，告诉浏览器不要缓存此内容
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expire", 0);
        RandomValidateCode randomValidateCode = new RandomValidateCode();
        try {
            randomValidateCode.getRandomCode(request, response);// 输出图片方法
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/Login", method = RequestMethod.POST)
    @ResponseBody
    public String Login(HttpServletRequest request) {
        //applicationContext.

        ResultObj resultObj = new ResultObj();
        resultObj.setCode(ResultObj.CODE_SUCCESS);
        try {
            Map<String, String> map = this.showRequestParameters(request);
            String randomCode = (String) request.getSession().getAttribute(RandomValidateCode.RANDOMCODEKEY);
            String code = map.get("code");
            if (!code.toLowerCase().equals(randomCode.toLowerCase())) {
                logger.info(code + "<<<randomCode>>>" + randomCode);
                throw new MyRunTimeExcption(MessageConstant.CODE_ERRO);
            }
            AdminUser adminUser = adminUserService.login(this.showRequestParameters(request));
            if (adminUser == null) {
                throw new MyRunTimeExcption(MessageConstant.USERNAME_PASSWORD_ERRO);
            }
            request.getSession().setAttribute(Constant.SESSION_KEY_ADMDIN_USER_LOGIN, adminUser);


            resultObj.setMsg(MessageConstant.LOGIN);
        } catch (MyRunTimeExcption myRunTimeExcption) {
            myRunTimeExcption.printStackTrace();
            resultObj.setCode(ResultObj.CODE_FAIL);
            resultObj.setMsg(myRunTimeExcption.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            resultObj.setCode(ResultObj.CODE_FAIL);
            resultObj.setMsg(e.getMessage());
        }

        return resultObj.toJson();

    }

    /**
     * 跳转到修改页面
     *
     * @param request
     * @param tid
     * @return
     */
    @RequestMapping(value = "/updatePassWord")
    @ResponseBody
    public ModelAndView updatePassWord(HttpServletRequest request, Integer tid) {
        Map<String, String> map = this.showRequestParameters(request);
        ModelAndView mov = new ModelAndView();
        mov.setViewName("/admin/user/change-password");
        mov.addObject("map",map);
        return mov;
    }

    /**
     * 用户列表
     * @param request
     * @param page
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/getUserList")
    public ModelAndView getUserList(HttpServletRequest request, Integer page, Integer pageSize) {
        ModelAndView mov = new ModelAndView();
        mov.setViewName("/admin/user/getUserList");

        /*if (page == null || page == 0) {
            page = Constant.PAGENUM;
        }
        // 设置每页记录数
        if (pageSize == null || pageSize == 0) {
            pageSize = Constant.PAGESIZENum;
        }
        PageHelper.startPage(page, pageSize);*/
        Map<String, String> map = this.showRequestParameters(request);
        List<Map<String, Object>> userList = adminUserService.getUserList(map);

        /*PageInfo<Map<String, Object>> pageinfo = new PageInfo<Map<String, Object>>(userList);
        mov.addObject("pageinfo", pageinfo);*/
        mov.addObject("userList", userList);
        mov.addObject("bean", map);
        return mov;

    }
    @RequestMapping(value = "/getUser")
    public ModelAndView getUser(HttpServletRequest request) {
        ModelAndView mov = new ModelAndView();
        mov.setViewName("/admin/user/adminUser-add");
        Map<String, String> map = this.showRequestParameters(request);
        List<Role> roleList = roleService.getRoleList(null);
        mov.addObject("roleList", roleList);
        try {
            AdminUser adminUser = adminUserService.getUser(map);
            mov.addObject("adminUser1", adminUser);

        } catch (MyRunTimeExcption e) {
            e.printStackTrace();
        }
        return mov;

    }
    /**
     * 修改后台用户信息
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/modifyUser",  method = RequestMethod.POST)
    @ResponseBody
    public String modifyUser(HttpServletRequest request) {

        ResultObj resultObj = new ResultObj();
        resultObj.setCode(ResultObj.CODE_FAIL);
        try {
            Map<String, String> map = this.showRequestParameters(request);
            adminUserService.modifyUser(map);
            resultObj.setCode(ResultObj.CODE_SUCCESS);
            resultObj.setMsg("成功！");
        } catch (MyRunTimeExcption myRunTimeExcption) {
            resultObj.setMsg(myRunTimeExcption.getMessage());
            myRunTimeExcption.printStackTrace();
        } catch (Exception e) {
            resultObj.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return resultObj.toJson();
    }

    /**
     * 修改密码
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/modifyPassword", method = RequestMethod.POST)
    @ResponseBody
    public String modifyPassword(HttpServletRequest request) {

        ResultObj resultObj = new ResultObj();
        resultObj.setCode(ResultObj.CODE_FAIL);
        try {
            Map<String, String> map = this.showRequestParameters(request);

            AdminUser adminUser = adminUserService.selectAdminById(map);
            String PageOldPassWord = MD5Tools.MD5(map.get("oldPassWord"));
            String OldPassWord = adminUser.getPassWord();

            if (PageOldPassWord.equals(OldPassWord)) {
                adminUserService.modifyUser(map);
                resultObj.setCode(ResultObj.CODE_SUCCESS);
                resultObj.setMsg(MessageConstant.MODIFY_PASSWORD_SUCCESS);
            } else {
                resultObj.setCode(ResultObj.CODE_FAIL);
                resultObj.setMsg(MessageConstant.PASSWORD_ERRO);
            }

        } catch (MyRunTimeExcption myRunTimeExcption) {

            resultObj.setMsg(myRunTimeExcption.getMessage());
            myRunTimeExcption.printStackTrace();
        } catch (Exception e) {
            resultObj.setMsg(e.getMessage());
            e.printStackTrace();
        }

        return resultObj.toJson();

    }

    /**
     * 重置密码
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/resetPassword")
    @ResponseBody
    public String resetPassword(HttpServletRequest request) {
        System.out.println("=================================resetPassword==========================================>>>>>>");

        ResultObj resultObj = new ResultObj();
        resultObj.setCode(ResultObj.CODE_FAIL);
        try {
            Map<String, String> map = this.showRequestParameters(request);
            map.put("passWord", "123456");
            AdminUser adminUser = adminUserService.selectAdminById(map);
            adminUserService.modifyUser(map);
            resultObj.setCode(ResultObj.CODE_SUCCESS);
            resultObj.setMsg(MessageConstant.PASSWORD_RESET_SUCCESS);
        } catch (MyRunTimeExcption myRunTimeExcption) {
            resultObj.setMsg(myRunTimeExcption.getMessage());
            myRunTimeExcption.printStackTrace();
        } catch (Exception e) {
            resultObj.setMsg(e.getMessage());
            e.printStackTrace();
        }

        return resultObj.toJson();

    }

    @RequestMapping(value = "/loginOut", method = RequestMethod.POST)
    @ResponseBody
    public String loginOut(HttpServletRequest request) {
        System.out.println("===============================loginOut============================================>>>>>>");

        ResultObj resultObj = new ResultObj();
        resultObj.setCode(ResultObj.CODE_SUCCESS);
        try {
            request.getSession().invalidate();
        } catch (MyRunTimeExcption myRunTimeExcption) {
            myRunTimeExcption.printStackTrace();
            resultObj.setCode(ResultObj.CODE_FAIL);
            resultObj.setMsg(myRunTimeExcption.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            resultObj.setCode(ResultObj.CODE_FAIL);
            resultObj.setMsg(e.getMessage());
        }
        return resultObj.toJson();
    }
}
